<template>
  <div>
    <h3>体能测评趋势报表</h3>
    <div class="container">
      <div style="min-height: 100px;">
        <el-checkbox-group v-model="searchForm.packageId" size="mini" style="display: flex;flex-wrap: wrap;align-items: center;">
          <el-checkbox style="margin: 10px 0;margin-right: 20px;" :label="item.packageId" border v-for="item,index in packages" :key="index">{{item.name}}</el-checkbox>
        </el-checkbox-group>
        <el-row  type="flex" :gutter="2" style="margin: 10px 0;">
          <el-col :span="4">
            <el-button-group style="display: flex;">
              <el-button type="success" :icon="!loading?'el-icon-download':'vxe-icon--refresh roll'" size="small" :disabled="loading" @click="exportDataAll">导出</el-button>
              <el-button type="success" :icon="!loading?'el-icon-printer':'vxe-icon--refresh roll'" size="small" :disabled="loading" @click="printEventAll">打印</el-button>
            </el-button-group>
          </el-col>
          <el-col :span="4">
            <el-date-picker size="small" v-model="doubleDate" type="daterange" align="left" unlink-panels style="width: 90%;"
              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions">
            </el-date-picker>
          </el-col>
          <el-col :span="3">
            <el-select  v-model="searchForm.sportId" size="small" collapse-tags @change="sportChange"
              filterable clearable placeholder="运动项目">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select  v-model="searchForm.coachId" size="small" collapse-tags @change="coachChange"
              filterable clearable placeholder="教练员">
              <el-option :label="item" :value="key" v-for="(item,key,index) in coachData" :key="index">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button-group style="display: flex;">
              <el-select  v-model="searchForm.playerId" multiple size="small" collapse-tags
                filterable clearable placeholder="运动员">
                <el-option :label="item" :value="key" v-for="(item,key,index) in playerData" :key="index">
                </el-option>
              </el-select>
              <el-button @click="searchForm.playerId=Object.keys(playerData)" type="primary" size="small">全选</el-button>
            </el-button-group>
          </el-col>
          <el-col :span="3" style="display: flex;">
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="personTendencyReportPreview" style="margin: 0 10px;">搜索</el-button>
            <vxe-button @click="searchClear" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
          </el-col>
          <el-col :span="3">
            <vxe-input style="float: right;width: 100%;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
              @input="searchEvent"></vxe-input>
          </el-col>
        </el-row>
      </div>
      <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row
        :loading="loading" :data="dataList" @sort-change="sortChange">
        <vxe-table-column field="name" title="姓名" sortable></vxe-table-column>
        <vxe-table-column field="createDate" title="时间" sortable></vxe-table-column>
        <vxe-table-column field="" title="操作" width="110">
          <template #default="{ row }">
            <template v-if="row.existence">
              <el-tooltip class="item" effect="dark" content="查看报表" placement="top-start">
                <el-button @click="prevewReport(row)" type="primary" circle size="medium" icon="el-icon-view"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="打印报表" placement="top-end">
                <el-button @click="printReport(row)" type="primary" circle size="medium" icon="el-icon-printer"></el-button>
              </el-tooltip>
            </template>
            <template v-else>
              <span>未记录</span>
            </template>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
      </vxe-pager>
    </div>
    <!-- 查看 -->
    <vxe-modal v-model="previewModal" title="报表查看" height="800" show-zoom resize width="1000" show-footer>
      <template #default>
        <tendencyReportPreview :previewData="previewData" :dict_meta="dict_meta"/>
        <p>报表名称(保存报表需要先给该报表起个名字)</p>
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="reportName"></el-input>
        <p>评价</p>
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入内容" v-model="reportMemo"></el-input>
      </template>
      <template #footer>
        <el-button @click="saveEvent" type="primary" icon="el-icon-s-promotion" size="mini">保存</el-button>
      </template>
    </vxe-modal>
    <!-- 打印 -->
    <vxe-modal v-model="printModal" title="打印预览" height="800" show-zoom resize width="1000" show-footer>
      <template #default>
        <tendencyReportPreview ref="myPrint" id="myPrint" :previewData="previewData" :dict_meta="dict_meta"/>
      </template>
      <template #footer>
        <el-button @click="printEvent" type="primary" icon="el-icon-printer" size="mini">打印</el-button>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import {
    sport_by_org,
    coach_by_org,
    currentRolePlayer,
    pcm4player,
    coach_by_sport
  } from '@/api/dict.js'
  import {personTendencyReportPreview,personTendencyReport,saveTendencyReport,bf_meta_all} from '@/api/meta.js'
  import tendencyReportPreview from '@/components/bfViewTable/personTendencyReportPreview.vue'
  export default {
    components: {
      tendencyReportPreview
    },
    data() {
      return {
        doubleDate: [],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近半年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit('pick', [start, end]);
            }
          },  ]
        },
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        searchProps: [],
        dict_coach: {},
        dict_player: {},
        dict_sport: {},
        dict_meta: {},
        searchForm: {
          sportId: '',
          coachId: '',
          playerId: [],
          packageId: [],
        },
        dict_sport: {},
        dict_coach: {},
        coachData: {},
        dict_player: {},
        playerData: {},
        previewModal: false,
        printModal: false,
        previewData: {
          playerInfo: [],
          tendencyData: [],
        },
        reportName: '',
        reportMemo: '',
        packages: [
          {
            packageId: 1,
            name: '动作质量七项必填',
          },
          {
            packageId: 2,
            name: '综合力量三选一',
          },
          {
            packageId: 3,
            name: '上肢爆发力二选一',
          },
          {
            packageId: 4,
            name: '局部肌肉力量二选一',
          },
          {
            packageId: 5,
            name: '耐力三选一',
          },
          {
            packageId: 6,
            name: '协调能力二选一',
          },
          {
            packageId: 7,
            name: '加速能力二选一',
          },
          {
            packageId: 8,
            name: '下肢爆发力二选一',
          },
          {
            packageId: 9,
            name: '灵敏性三选一',
          }
        ],
        search: false,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.personTendencyReportPreview()
      })
    },
    watch: {
      filterName(val) {
        if(!val){
          this.page = {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0,
          }
          this.search = false
          this.findList()
        }
      }
    },
    methods: {
      saveEvent() {
        let data = {
          reportData: JSON.stringify(this.previewData),
          name: this.reportName,
          memo: this.reportMemo
        }
        saveTendencyReport(data).then(res=>{
          if(res.code === 200) {
            this.$message.success('保存成功！')
          }else{
            this.$message.error(res.message)
          }
        })
      },
      printEvent() {
        this.$refs.myPrint.print()
        setTimeout(()=>{
          const divEl = document.getElementById('myPrint')
          this.$XPrint({
            sheetName: '体能测评个人报表',
            content: divEl.innerHTML
          })
        },200)
      },
      prevewReport(row){
        let date = row.createDate.split('至')
        let data = {
          playerId: row.playerId,
          monthBegin: date[0]+'-01',
          monthEnd: date[1]+'-01',
          packageIds: this.searchForm.packageId.join(',')
        }
        personTendencyReport(data).then(res=>{
          if(res.code === 200) {
            this.previewData = res.data
            this.reportName = row.name+row.createDate+'趋势分析报表'
          }
          this.previewModal = true
        })
      },
      printReport(row){
        let date = row.createDate.split('至')
        let data = {
          playerId: row.playerId,
          monthBegin: date[0]+'-01',
          monthEnd: date[1]+'-01',
        }
        personTendencyReport(data).then(res=>{
          if(res.code === 200) {
            this.previewData = res.data
          }
          this.printModal = true
        })
      },
      exportDataAll() {
        this.$refs.XTable.exportData({
          filename: '体能测评趋势报表',
          data: this.search?this.dataList:this.defaultDataList
        })
      },
      printEventAll() {
        let topHtml = '<h2>体能测评趋势报表</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '体能测评趋势报表',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      searchClear() {
        this.searchForm = {
          sportId: '',
          coachId: '',
          playerId: [],
          packageId: []
        }
        this.personTendencyReportPreview()
      },
      personTendencyReportPreview() {
        let data = {}
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.coachId) data.coachId = this.searchForm.coachId
        if(this.searchForm.playerId) data.playerIds = this.searchForm.playerId.join(',')
        if(this.searchForm.packageId) data.packageIds = this.searchForm.packageId.join(',')
        if (this.doubleDate) {
          data.monthBegin = this.$moment(this.doubleDate[0]).format('YYYY-MM-DD')
          data.monthEnd = this.$moment(this.doubleDate[1]).format('YYYY-MM-DD')
        }
        this.loading = true
        personTendencyReportPreview(data).then(res=>{
          if(res.code === 200) {
            if(res.data.length!=0){
              this.page = {
                currentPage: 1,
                pageSize: 10,
                totalResult: 0
              }
              this.search = true
              this.defaultDataList = res.data
              this.searchProps = Object.keys(res.data[0])
            }else{
              this.defaultDataList = []
            }
          }else{
            this.defaultDataList = []
            this.$message.error(res.message)
          }
        }).then(()=>{
          this.loading = false
          this.findList()
        })
      },
      sportChange (val) {
        this.searchForm.coachId = ''
        this.searchForm.playerId = ''
        this.coachData = {}
        this.playerData = {}
        let sportId = this.searchForm.sportId || val
        if(sportId){
          coach_by_sport({sportId:sportId}).then(res=>{
            this.coachData = res
          })
          pcm4player({sportId:sportId}).then(res=>{
            this.playerData = res
          })
        }
      },
      coachChange (val) {
        this.searchForm.playerId = ''
        this.playerData = {}
        let coachId = this.searchForm.coachId || val
        let data = {}
        if(this.searchForm.sportId) data.sportId = this.searchForm.sportId
        if(this.searchForm.coachId) data.coachId = this.searchForm.coachId
        if(coachId){
          pcm4player(data).then(res=>{
            this.playerData = res
          })
        }
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          this.doubleDate = [start,end]
          sport_by_org().then(res => {
            this.dict_sport = res
          })
          coach_by_org().then(res => {
            this.dict_coach = res
            this.coachData = res
          })
          bf_meta_all().then(res=>{
            let dict = {}
            res.data.forEach(item=>{
              dict[item.metaId] = item.name
            })
            this.dict_meta = dict
          })
          currentRolePlayer().then(res=>{
            this.dict_player = res
            this.playerData = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
            currentPage: 1,
            pageSize: this.dataList.length,
            totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
        if(!this.search){
          this.page.pageSize = this.defaultDataList.length
          this.findList()
        }else{
          this.page.pageSize = this.dataList.length
        }
      },
      findList() {
        setTimeout(() => {
          this.loading = false
          this.page.totalResult = this.defaultDataList.length
          this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
            .pageSize, this.page.currentPage * this.page.pageSize)
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
.container {
    padding: 10px;
    background-color: #FFFFFF;
  }
</style>
